package com.shengyin.ec.controller.order;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.util.WebUtils;

import com.shengyin.ec.controller.common.Constant;
import com.shengyin.ec.controller.shopcart.Item;
import com.shengyin.ec.controller.shopcart.ShopCartForm;
import com.shengyin.ec.exception.ControllerException;
import com.shengyin.ec.model.entity.ClusterCompany;
import com.shengyin.ec.model.entity.Delivery;
import com.shengyin.ec.model.entity.Goods;
import com.shengyin.ec.model.entity.OrderItem;
import com.shengyin.ec.model.entity.Orders;
import com.shengyin.ec.model.entity.Payment;
import com.shengyin.ec.model.entity.Personal;
import com.shengyin.ec.model.entity.Receiver;
import com.shengyin.ec.service.account.ReceiverService;
import com.shengyin.ec.service.delivery.DelieveryService;
import com.shengyin.ec.service.goods.GoodsService;
import com.shengyin.ec.service.order.OrderDetailService;
import com.shengyin.ec.service.order.OrderService;
import com.shengyin.ec.service.payment.PaymentService;

@Controller
public class OrderController {
	@Autowired
	GoodsService goodsService;
	
	@Autowired
	PaymentService paymentService;
	
	@Autowired
	DelieveryService deliveryService;
	
	@Autowired
	ReceiverService receiverService;
	
	@Autowired
	OrderService orderService;
	
	@Autowired
	OrderDetailService orderDetailService;
	
	@RequestMapping("/toSubmitOrders.do")
	public String createOrders(HttpServletRequest request,ModelMap modelMap){
		
		ShopCartForm shopCart=(ShopCartForm) WebUtils.getSessionAttribute(request, "shopCart");
		
		if(shopCart==null)
			return "redirect:/toIndex.do";
		
		//取得商品
		String ids[] = request.getParameterValues("goodsid");
		//取得收货人信息
		String receiverId=request.getParameter("receiverId");
		
		//到得支付方式
		String paymentId = request.getParameter("paymentId");
		
		String delieveryId = request.getParameter("delieveryId");
		
		
		String note=request.getParameter("note");
		String inv_payee = request.getParameter("inv_payee");
		String invoiceType=request.getParameter("invoiceType");
		
		System.out.println("note:"+note+"   "+"inv_payee " +inv_payee+"   invoiceType"+invoiceType);
		
		
		Personal user=(Personal) WebUtils.getSessionAttribute(request, "user");
		
		if(delieveryId==null||receiverId==null||paymentId==null||user==null||ids==null||ids.length==0)
			return "redirect:/toShopCart.do";
		
		
		List<Goods> goodsList=goodsService.getGoodsListBySelected(ids);
		Long receiverid=Long.valueOf(receiverId);
		Long paymentid=Long.valueOf(paymentId);
		Long delieveryid=Long.valueOf(delieveryId);
		
		List<Item> itemList =shopCart.getBoughtGoods(goodsList);
		Receiver receiver = receiverService.getReceiver(receiverid);
		Payment payment=paymentService.getPaymentById(paymentid);
		Delivery delivery=deliveryService.getDeliveryById(delieveryid);
		
		Orders orders = new Orders();
		
		
		for(Item item:itemList){
			OrderItem orderItem = new OrderItem();
			orderItem.setGoods(item.getGoods());
			orderItem.setQuantity(item.getQuantity());
			orderItem.setSubtotal(item.getSubtotal());
			orders.addOrderItem(orderItem);
		}
		
		
		
		
		orders.setUser(user);
		orders.setReceiver(receiver);
		orders.setPayment(payment);
		orders.setDelivery(delivery);
		
		orders.setInv_payee(inv_payee);
		orders.setInvoiceType(invoiceType);
		orders.setNote(note);
		
		Date nowDate =new Date();
		orders.setCreateDate(nowDate);
		orders.setOrderState(Constant.ORDERSTATE_NOT_PAY);
		
		shopCart.caculateBoughtItemPrice(itemList);
		shopCart.caculateBoughtItemMarketPrice(itemList);
		orders.setTotalPrice(shopCart.getBoughtItemprice());
		
		
		
		
		orderService.createOrder(orders);
		
		
		
		modelMap.addAttribute("delivery", delivery);
		modelMap.addAttribute("totalPrice", orders.getTotalPrice());
		modelMap.addAttribute("payment", payment.getPaymentName());
		modelMap.addAttribute("orderID", orders.getOrderId());
		
		shopCart.clearBoughtGoods(goodsList);
		return "/view/order/orderSuccess";
		
	}
   //orders about shengyin
	@RequestMapping(value="toOrder.do")
	public String toAllOrder(Model model,HttpServletRequest request){
			
		int type = Integer.parseInt(request.getParameter("type"));
		List<Orders> ordersList = orderService.getAllOrder(type,0,10);
		long maxSize = orderService.getAllOrder(type).size();
		model.addAttribute("ordersList",ordersList);
		model.addAttribute("maxSize",maxSize);
		model.addAttribute("type",type);
		
		return "/admin/orders/orderList";
		
	}
	
	@RequestMapping("searchOrderByOrderId.do")
	public String searchOrderByOrderId(HttpServletRequest request){
		
		String orderId = request.getParameter("orderId");
		List<Orders> ordersList = orderService.getOrderByOrderId(orderId,0,10);
	    long maxSize = orderService.getOrderByOrderId(orderId).size();
	    HttpSession session = request.getSession();
	    session.setAttribute("ordersList", ordersList);
	    session.setAttribute("maxSize", maxSize);
	    session.setAttribute("type", request.getParameter("type"));
	    
	    return "/admin/orders/orderList";
	    
	}
	
	@RequestMapping("searchOrderByStat.do")
	public String searchOrderByStat(HttpServletRequest request){
		
		String orderStat = request.getParameter("orderStat");
		
		
		HttpSession session = request.getSession();
		if(orderStat == "0")
			return "redirect:/toOrder.do";
		
		List<Orders> ordersList = orderService.getOrderByStat(orderStat,0,10);
		long maxSize = orderService.getOrderByStat(orderStat).size();
		session.setAttribute("ordersList", ordersList);
		session.setAttribute("maxSize", maxSize);
		session.setAttribute("type", request.getParameter("type"));

	    return "/admin/orders/orderList";
	}
	
	@RequestMapping("searchOrderByDate.do")
	public String searchOrderByDate(HttpServletRequest request,Model model){
		
	    String date = request.getParameter("date");
	    
		
		if(date == "0")
			return "redirect:toOrder.do";
		
			
			List<Orders> ordersList = orderService.getOrderByDate(date,0,10);
		    long maxSize = orderService.getOrderByDate(date).size();
		    model.addAttribute("ordersList", ordersList);
		    model.addAttribute("maxSize", maxSize);
		    model.addAttribute("type", request.getParameter("type"));
		

	    return "/admin/orders/orderList";
	    
	    
	}
	
	/**
	 * 买家查看订单列表user/toOrderList.do
	 */
	@RequestMapping("/user/toOrderList.do")
	public String toOrderList(HttpServletRequest request,ModelMap modelMap){
		Personal user=(Personal) WebUtils.getSessionAttribute(request, "user");
		List<Orders> orderList = orderService.getOrdersByUserId(user.getId());
		modelMap.addAttribute("orderList", orderList);
		return "/view/order/orderList";
	}
	
    /*
     * spring mvc异常处理方法，在controller发生异常，可以以抛出ControllerException，以供捕获
     * */
    @ExceptionHandler({ControllerException.class})  
	   public String exception(ControllerException e,HttpServletRequest request) {  
	       request.setAttribute("error", e.getMessage());
	        return "/admin/error/error";  
	    }  
}
